package org.tsisa.smsplugin;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class Conversation {
	public String address;
	public ArrayList<ConversationCell> messages;
	
	Conversation(String addr){
		address = addr;
		messages = new ArrayList<ConversationCell>();
	}
	
	public void updateConversation(ConversationCell message){
		messages.add(message);
	}
	
	public void sortConversation(final String sort){
		Collections.sort(messages,new Comparator<ConversationCell>() {
			@Override
			public int compare(ConversationCell c1, ConversationCell c2) {
				// TODO Auto-generated method stub
				if(sort.compareTo("asc")==0){
					if(c1.getDate().compareTo(c2.getDate())<0){
						return -1;
					}
					else if(c1.getDate().compareTo(c2.getDate())>0){
						return 1;
					}
					else{
						return 0;
					}
				}
				else{
					if(c1.getDate().compareTo(c2.getDate())<0){
						return 1;
					}
					else if(c1.getDate().compareTo(c2.getDate())>0){
						return -1;
					}
					else{
						return 0;
					}
				}
			}
		});
	}
	
	public JSONArray parseMessagesToJSONArray(int from, int to){
		JSONArray conversation = new JSONArray();
		if(messages.size()<to && messages.size()>from){
			to = messages.size();
		}
		for(int i=from; i<to; i++){
			JSONObject text = new JSONObject();
			try {
				text.put("date", messages.get(i).getDate());
				text.put("message", messages.get(i).getMessage());
				text.put("user", messages.get(i).getAction());
				conversation.put(text);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return conversation;
	}
	
	public String getAddress(){
		return address;
	}
}
